package com.azdebugit.list.arraylist.settest;

/*
 * @author 小沐
 * @param <E>
 */
public class SetArrayList3<E> {
    private Object[] elementData;  // 数组
    private int size;              // 长度
    private static final int DEFALT_CAPACITY = 10;    //默认数组长度

    public SetArrayList3() {
        elementData = new Object[DEFALT_CAPACITY];
    }

    public SetArrayList3(int capacity) {
        // 检查capacity
        if (capacity < 0) {
            throw new RuntimeException("容器容量不能为负数");
        } else if (capacity == 0) {
            elementData = new Object[DEFALT_CAPACITY];
        } else {
            elementData = new Object[capacity];
        }
    }

    public void add(E element) {
        if (size == elementData.length) {
            Object[] newobjects = new Object[/* elementData.length*2 */elementData.length + (elementData.length << 1)];

            System.arraycopy(elementData, 0, newobjects, 0, elementData.length);
            elementData = newobjects;
        }
        elementData[size++] = element;
    }

    public E get(int index) {
        // TODO Auto-generated method stub
        checkRange(index);
        return (E) elementData[index];
    }

    public void set(E element, int index) {
        checkRange(index);
        elementData[index] = element;
    }

    public void checkRange(int index) {

        if (index < 0 || index > size - 1) {
            throw new RuntimeException("索引不合法！" + index);   // 抛出异常
        }
    }

    @Override
    public String toString() {  // 重写toString方法
        // TODO Auto-generated method stub
        StringBuilder sBuilder = new StringBuilder();
        //a,b,c
        sBuilder.append("[");

        sBuilder.setCharAt(sBuilder.length() - 1, ']');

        return sBuilder.toString();
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        SetArrayList3 s1 = new SetArrayList3(20);
        for (int i = 0; i < 20; i++) {
            s1.add("#" + i);
        }
        s1.set("worder", 1);
        System.out.println(s1);
        System.out.println(s1.get(10));
    }
}

